package com.socket.learing.udp;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * Created by 张波 on 2019/12/10.
 */
@Slf4j
public class ReceiveService {

    public static void main(String[] args) throws IOException {
        DatagramSocket datagramSocket = new DatagramSocket(20000);

        byte[] buf = new byte[512];
        DatagramPacket datagramPacket = new DatagramPacket(buf, 0, buf.length);
        datagramSocket.receive(datagramPacket);

        String msg = new String(datagramPacket.getData(), 0, datagramPacket.getLength());
        log.info("接收到信息，IP：{},port:{},data:{}", datagramPacket.getAddress().getHostAddress(),
                datagramPacket.getPort(), msg);
        byte[] bytes = "回复消息".getBytes();
        DatagramPacket responsePacket = new DatagramPacket(bytes, bytes.length, datagramPacket.getAddress(),
                datagramPacket.getPort());
        datagramSocket.send(responsePacket);
        System.out.println("消息回复完成，程序结束");
        datagramSocket.close();
    }
}
